import re
import wsgiref.handlers
from google.appengine.api import urlfetch 
from google.appengine.ext import webapp
from google.appengine.api import memcache
##########################################


def get_news_by_id(news_ID) :
	
	f = ('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n'
	     '<html><head>\n'
	     '<title>heise.de newsreader</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n'
	     '</head><body>\n'
	     '<form action="">\n'
	     '<input type="button" value="NEXT NEWS BY ID" onClick="window.location.pathname = \'/read/news/\' + (parseInt(window.location.pathname.slice(11)) + 1).toString()">\n'
	     '</form>\n'
	     '<div style="width:400px; float: left; padding: 20px; border: 2px solid black">\n')
	
	raw_html_heise_news = re.findall('.*\n', urlfetch.fetch("http://heise-online.mobi/news/" + news_ID).content)
	
	found_news = False
	
	for ii in range(len(raw_html_heise_news)):
		if raw_html_heise_news[ii].find('<h2>') > -1 :
			f += '<p><h5>' + raw_html_heise_news[ii][4:-6] + '</h5></p>'
		
		if raw_html_heise_news[ii].find('<div id="artikel">') > -1 :
			found_news = True
			permission_to_write = True
			while True:
				ii += 1
				line = raw_html_heise_news[ii]
				if line.find('<div class="bild">') > -1 :
					f += '<p style="font-size:small"> | removed image | </p>'
					ii += 3
					l = raw_html_heise_news[ii]
					if l.find('</div>') > -1 :
					    if l.find('<div class="bild">') > -1 :                                                
						f += l[6:-19]
						ii += 3
						l = raw_html_heise_news[ii]

						if l.find('</div>') > -1 :
						    f += l[6:]
						    
						else:
						    f += l

					    else:
						f += l[6:]
					else:
						f += l
		
				elif line.find('<div id="bilderstrecke_vorschau">') > -1 :
					f += '<p style="font-size:small">| removed image gallery |</p>'
					ii += 9
		
				elif line.find('<!-- mobiad') > -1 :
					permission_to_write = False

				elif line.find('<!-- /mobiad') > -1 :
					permission_to_write = True

				elif line.find('<div id="inhalt-unten">') > -1 :
					break

				elif permission_to_write :
					f += line

			break
		    

        f += '<div style="clear: left">'

	f += '<br>(<a href="http://heise-online.mobi/news/'+ news_ID +'">mobiler Artikel</a>)\n'
	f += '<br>(<a href="http://heise.de/newsticker/meldung/'+ news_ID +'">orginaler Artikel</a>)\n'
	    
	f += ('<br><br><br><br></div>'
	      '</body></html>')

	
	if not found_news :
	    f = ('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n'
		 '<html><head>\n'
		 '<title>redirecting ..</title><meta http-equiv="refresh" content="0; URL=../../read/news/' + str(int(news_ID) + 1) + '">\n'
		 '</head><body></body></html>')

	    return f
	
	if (int(news_ID) > int(memcache.get("last_ID"))) :
		memcache.replace("last_ID", news_ID)
	
	return f


class set_last_id(webapp.RequestHandler) :
	def get(self, news_ID) :
                memcache.add(key="last_ID", value=news_ID)
		memcache.replace("last_ID", news_ID)



							
class get_first_unread_news(webapp.RequestHandler) :
	def get(self) :                
		news_ID = memcache.get("last_ID")
		
		self.response.out.write('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n'
					'<html><head>\n'
					'<title>redirecting ..</title><meta http-equiv="refresh" content="0; URL=/read/news/' + news_ID + '">\n'
					'</head><body></body></html>')
		


class get_news(webapp.RequestHandler) :
	def get(self, news_ID) :
		self.response.out.write(get_news_by_id(news_ID))


def main() :
	application = webapp.WSGIApplication([('/read/news/(\d\d\d\d\d\d)', get_news),
                                              ('/set_last_id/(\d\d\d\d\d\d)', set_last_id),
                                              ('/.*', get_first_unread_news)])
	
	wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
	main()
